#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        std::cerr << "fcntl" << std::endl;
        exit(-1);
    }
    // 这里是 F_SETFL 而不是 F_SETFD
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    SetNonBlock(0);

    while (1)
    {
        char buf[1024] = {0};
        ssize_t s = read(0, buf, sizeof(buf) - 1);
        if(s > 0)
        {
            buf[s] = 0;
            write(1, buf, strlen(buf));
            printf("read success, s: %d, errno: %d\n", s, errno);
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cerr << "数据还未准备好 : "<< errno << std::endl;
                sleep(1);
                continue;
            }
        }
    }
    return 0;
}

